package com.qingzhu.component.lock.starter.config;

import com.qingzhu.component.lock.annotation.starter.EmptyCommonBeanAnnotation;
import com.qingzhu.component.lock.common.constant.AutoConfig;
import com.qingzhu.component.lock.starter.scanner.EmptyLockComponentBeanDefinitionScanner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import java.lang.annotation.Annotation;
import java.util.List;

import static java.util.Arrays.asList;

/**
 * lock相关组件的bd注册器(当lock.enable = false 或者不填写时，进行注入)
 * @author xiangjz
 * @version 1.0
 * @date 2021/1/15 9:54
 */
@Slf4j
@ConditionalOnProperty(prefix = AutoConfig.CONFIG_PREFIX, name = "enable", havingValue = "false", matchIfMissing = true)
@AutoConfigureBefore(LockComponentAutoConfiguration.class)
public class EmptyLockComponentBeanDefinitionRegisterer implements BeanDefinitionRegistryPostProcessor,
        EnvironmentAware,
        BeanClassLoaderAware {

    private Environment environment;

    private ClassLoader classLoader;

    private final static List<Class<? extends Annotation>> serviceAnnotationTypes = asList(
            EmptyCommonBeanAnnotation.class
    );

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        // 搜寻 LockCommonBeanAnnotation 注解的所有bean
        EmptyLockComponentBeanDefinitionScanner scanner = new EmptyLockComponentBeanDefinitionScanner(registry,
                this.environment, this.classLoader, serviceAnnotationTypes);
        serviceAnnotationTypes.forEach(annotationType -> scanner.addIncludeFilter(new AnnotationTypeFilter(annotationType)));

        // 调用scan方法，将所有匹配的类加入容器
        scanner.scan(AutoConfig.COMPONENT_PACKAGE_PATH);
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
}
